package com.belazy.library.core.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.belazy.library.model.request.ListRequest;
import com.belazy.library.model.response.PageResponse;
import org.springframework.util.StringUtils;

/**
 * @Description <p> Controller基础抽象类  </p>
 * @Author chupeng.tang
 * @CreateTime 2023/5/19 17:29
 * @Version 1.0
 */
public abstract class BaseController {
    private static final String ASC = "ASC";
    /**
     * 构建分页数据模型
     * @param page
     * @param <T>
     * @return
     */
    public <T> PageResponse<T> toPage(Page<T> page) {
        PageResponse<T> vo = new PageResponse<> ();
        vo.setRecords (page.getRecords ());
        vo.setSize (page.getSize ());
        vo.setOffset (page.getCurrent ());
        vo.setTotal (page.getTotal ());
        return vo;
    }
    /**
     * 排序
     * @param query
     * @param from
     */
    public <T> QueryWrapper<T> orderBy(QueryWrapper<T> query, ListRequest from) {
        String field = from.getField ();
        String sort = from.getSort ();
        if (!StringUtils.isEmpty (field)) {
            String[] str = field.split (",");
            boolean isAsc = ASC.equalsIgnoreCase (sort);
            for (String s :str){
                query.orderBy (true,isAsc ,s);
            }
        }
        return query;
    }
}
